package com.jzo2o.foundations.service.impl;


import cn.hutool.core.bean.BeanUtil;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

import com.jzo2o.es.core.ElasticSearchTemplate;
import com.jzo2o.es.utils.SearchResponseUtils;
import com.jzo2o.foundations.model.domain.ServeAggregation;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.ServeAggregationService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 国兴越
 * @version 1.0
 * Create by
 */
@Slf4j
@Service
public class ServeAggregationServiceImpl implements ServeAggregationService {

    @Resource
     private ElasticSearchTemplate elasticSearchTemplate;


    @Override
    public List<ServeSimpleResDTO> findServeList(String cityCode, Long serveTypeId, String keyword) {

     //查询构造语句
       SearchRequest.Builder builder = new SearchRequest.Builder();

       builder.query(query->query.bool(bool->{

           //匹配citycode
           bool.must(must->must.term(term->
                   term.field("city_code").value(cityCode)));



         //匹配关键字
           if(ObjectUtils.isNotEmpty(keyword)){

               bool.must(must->must.multiMatch(muLtiMatch->muLtiMatch.fields("serve_item_name")));
           }
           return bool;
       }));

       //排序 按照服务项升序
        List<SortOptions> sortOptions = new ArrayList<>();

        sortOptions.add(SortOptions.of(sortOption->sortOption.field(field->field.field("serve_item_sort_num").order(SortOrder.Asc))));

        builder.sort(sortOptions);

        //指定索引
        builder.index("serve_aggregation");

        //请求对象
        SearchRequest searchRequest = builder.build();

        SearchResponse<ServeAggregation> search = elasticSearchTemplate.opsForDoc().search(searchRequest, ServeAggregation.class);

        //如果搜索成功返回结果集

        if(SearchResponseUtils.isSuccess(search)){

            List<ServeAggregation> collect = search.hits().hits().stream().map(hit -> {

                ServeAggregation source = hit.source();
                return source;

            }).collect(Collectors.toList());


           List<ServeSimpleResDTO> serveSimpleResDTO = BeanUtil.copyToList(collect, ServeSimpleResDTO.class);

           return serveSimpleResDTO;

        }


        return Collections.emptyList();
    }
}
